package by.dkusch.aircompany.webapp.app;

import java.util.Set;

import javax.inject.Inject;

import org.apache.wicket.Session;
import org.apache.wicket.authroles.authentication.AuthenticatedWebSession;
import org.apache.wicket.authroles.authorization.strategies.role.Roles;
import org.apache.wicket.injection.Injector;
import org.apache.wicket.request.Request;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import by.dkusch.aircompany.model.tables.UserAccount;
import by.dkusch.aircompany.model.tables.UserGrant;
import by.dkusch.aircompany.model.tables.UserProfile;
import by.dkusch.aircompany.model.tables.enums.UserRole;
import by.dkusch.aircompany.services.UserService;

public class BasicAuthenticationSession extends AuthenticatedWebSession {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	@SuppressWarnings("unused")
	private static final Logger LOGGER = LoggerFactory.getLogger(BasicAuthenticationSession.class);

	private UserProfile user;
	private String userName;
	private Set<UserGrant> userGrants;
	private boolean isDba = false;
	private boolean isArc = false;

    private Roles resultRoles;

	@Inject
	private UserService userService;

    public BasicAuthenticationSession(final Request request) {
        super(request);
        Injector.get().inject(this);
    }

    public static BasicAuthenticationSession get() {
        return (BasicAuthenticationSession) Session.get();
    }

	@Override
	public boolean authenticate(final String userName, final String password) {
		boolean authenticationResult = false;
		final UserAccount account = userService.getAccountByEmail(userName);

		if (account != null) {
			this.user = userService.get(account.getId());
			if (user.getArcFl()) {
				this.isArc = true;
				this.user = null;
			} else {
				if (account.getPwd().equals(password)) {
					this.userGrants = userService.getGrants(user);
					this.userName = userName;
					this.isDba = user.getDbaFl();
					authenticationResult = true;
				}
			}
		}
		return authenticationResult;
	}

	@Override
	public Roles getRoles() {
		if (isSignedIn() && (resultRoles == null)) {
			resultRoles = new Roles();
			
			resultRoles.add(UserRole.sign_in.name());

			if (isDba) {
				resultRoles.add(UserRole.admin.name());
			} else {
				resultRoles.add(UserRole.user.name());
			}
			
		}
		return resultRoles;
	}

	@Override
	public void signOut() {
		super.signOut();
		user = null;
		userGrants = null;
		userName = null;
	}

	public UserProfile getUser() {
		return user;
	}

	public String getUserName() {
		return userName;
	}

	public boolean isUserDba() {
		return isDba;
	}

	public boolean isUserArc() {
		return isArc;
	}

	public Set<UserGrant> getUserGrants() {
		return userGrants;
	}

}
